package com.mdc.mansion.web.modules.system.utils;

import java.io.File;
import java.util.Date;

import com.mdc.mansion.common.util.DateUtils;
import com.mdc.mansion.common.util.SerialToolKit;
import com.mdc.mansion.common.util.StringUtils;
import org.apache.commons.io.FilenameUtils;
import org.springframework.web.multipart.MultipartFile;

import com.mdc.mansion.web.common.config.WebGlobal;

/**
 * 文件上传工具类
 */
public class UploadUtils {

	private static final String fileUploadPath = WebGlobal.getFileUploadPath();
	
	private static final String fileUrlPre = WebGlobal.getFileUrlPre();

	public static String[] uploadFile(MultipartFile uploadFile,String name,String prePath) throws Exception{
		String savePath=createSavePath(prePath);
		String fileName=createFileName(uploadFile.getOriginalFilename());
		String filePath=fileUploadPath+savePath+"/"+fileName;
		String fileUrl=fileUrlPre+savePath+"/"+fileName;
		String [] ret={filePath,savePath+"/"+fileName,fileUrl};
		File file = new File(filePath);
		if(!file.exists()){file.getParentFile().mkdirs();}
		uploadFile.transferTo(file);
		return ret;
	}

	private static String createFileName(String originalFilename) {
		String extension = FilenameUtils.getExtension(originalFilename);
		String name= SerialToolKit.uuid();
		return name+"."+extension;
	}

	private static String createSavePath(String prePath) {
		String format = DateUtils.format(new Date(), "yy/MM/dd");
		String savePath="/"+format;
		if(StringUtils.isNoneBlank(prePath)){
			savePath+="/"+prePath;
		}
		return savePath;
	}
}
